package start.demo01.StringAnalysis;

import org.junit.Test;

import java.beans.Encoder;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

public class URLAnalysis {
    public static void main(String[] args) throws UnsupportedEncodingException {
        URLAnalysis ana=new URLAnalysis();
        String _sa="";
        ana.split("http://www.baidu.com?a=123&b=456&c=789@");
    }
    public void split(String oldUrl) throws UnsupportedEncodingException {
        //\S 	匹配任何非空白字符。与 [^ \f\n\r\t\v] 等效。
        String regexURL="^(https?://)?[A-Za-z0-9_]+\\.[A-Za-z0-9_]+\\.[A-Za-z0-9_]+";
        String regexParam="^[a-zA-Z][a-zA-Z0-9_]*=\\S+";

        int index=oldUrl.indexOf("?");
        String url=oldUrl.substring(0,index);
        if(!url.matches(regexURL)){
            System.out.println("网址匹配失败，不是一个网址");
        }
        String param=oldUrl.substring(index+1);
        String[] paramList=param.split("&");
        boolean flag=true;
        Map<String,String> map=new HashMap<>();
        String u=url+"?";
        for(String node:paramList) {
            System.out.println(node);
            if (!node.matches(regexParam)) {//匹配失败
                System.out.println("输入参数格式不正确");
                flag = false;
                break;
            }
            int ind=node.indexOf("=");
            System.out.println("ind="+ind);
            u+=node.substring(0,ind+1)+URLEncoder.encode(node.substring(ind+1),"utf-8")+"&";
            map.put(node.substring(0,ind),URLEncoder.encode(node.substring(ind+1),"utf-8"));
        }
        if(flag){
            String newParam="?";
            System.out.println(map);
            u=u.substring(0,u.length()-1);
            System.out.println("u:"+u);
            Set<Map.Entry<String,String>> set=map.entrySet();
            Iterator iterator=set.iterator();
            //System.out.println(iterator.);
            while(iterator.hasNext()){
                newParam+=iterator.next()+"&";
            }
            newParam=newParam.substring(0,newParam.length()-1);
            String newUrl=url+newParam;
            System.out.println("参数"+newParam);
            System.out.println("网址："+newUrl);
        }
        System.out.println("---------------------------------------");
    }
//    public String transcoder(String param,String coding) throws UnsupportedEncodingException {//转码器
//        String newParam=new String(param.getBytes(),coding);//使用java默认编编码，在使用特定方式解码
//        return newParam;
//    }
}
